import React, {Component} from 'react';
import {Relax} from 'iflux2';
import {List} from 'immutable';

import {Popconfirm} from 'antd';
import Image from 'components/Image'
import {SortableElement, SortableContainer, arrayMove} from 'react-sortable-hoc';
import noop from 'util/noop'


const SortableItem = SortableElement(({val, delGoods}) => {
    return (
        <div className="sort-list-item">
            <Image src={val.image} alt={val.itemName} width={50} height={50} />
            <p>{val.itemName}</p>
            <span>{val.itemBn}</span>
            <div className="sort-row-delete">
                <Popconfirm title="确定删除该商品的排序？" placement="leftTop" onConfirm={()=>delGoods(val)}>
                    <button className="t-pointer">删除</button>
                </Popconfirm>
            </div>
        </div>
    )
});


const SortableList = SortableContainer(({items, delGoods}) => {
    return (
        <div className="sort-list">
            {
                items.map((val, index) => <SortableItem key={`item-${index}`} index={index} val={val} delGoods={delGoods}/>)
            }
        </div>
    )
});


@Relax
export default class GoodsList extends Component {


    static defaultProps = {
        goodsList: List(),
        querySortGoods: noop,
        setGoodsSort: noop,
        delGoods: noop
    }


    componentDidMount() {
        this.props.querySortGoods();
    }


    render() {
        const {goodsList} = this.props;

        if (goodsList.isEmpty()) {
            return (
                <div className="t-center">
                    <img src="http://pic.qianmi.com/BossNew/5.0/img/sort-empty.png" width="197" />
                    <span className="t-grayer">请添加您想要排序的商品或单品，用拖拽进行排序</span>
                </div>
            )
        }

        return <SortableList  axis="y"
                              lockAxis="y"
                              lockToContainerEdges={true}
                              items={goodsList.toJS()}
                              onSortEnd={({oldIndex, newIndex})=>this.onSortEnd({oldIndex, newIndex})}
                              delGoods={(val)=>this.delGoods(val)}/>
    }


    /**
     * 商品排序
     * @param oldIndex
     * @param newIndex
     */
    onSortEnd({oldIndex, newIndex}) {
        const {setGoodsSort, goodsList} = this.props;
        setGoodsSort(arrayMove(goodsList.toJS(), oldIndex, newIndex));
    }


    /**
     * 删除排序商品
     * @param goods
     */
    delGoods(goods) {
        this.props.delGoods(goods);
    }
}